package com.wangsong;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Hashtable;  
 
import sun.misc.BASE64Encoder;  
  
import com.google.zxing.BarcodeFormat;  
import com.google.zxing.EncodeHintType;  
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;  
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;  
import com.google.zxing.client.j2se.MatrixToImageWriter;   
public class QRCodeUtil {  
  
  
    public static String enCode(String contents) {   
    	String base64Code = null;
    	int width = 300, height = 300;   
    	Hashtable<Object, Object> hints = new Hashtable<Object, Object>(); 
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);   
        ByteArrayOutputStream bao = new ByteArrayOutputStream();  
		try {
			BitMatrix byteMatrix = new MultiFormatWriter().encode(new String(contents.getBytes("UTF-8"),"iso-8859-1"),BarcodeFormat.QR_CODE, width, height);
			MatrixToImageWriter.writeToStream(byteMatrix, "png", bao);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  catch (WriterException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        base64Code =Base64Code(bao.toByteArray());  
        return base64Code;   
    }   
      
    public static String  Base64Code(byte[] b) {  
        BASE64Encoder encoder = new BASE64Encoder();  
        StringBuilder pictureBuffer = new StringBuilder();  
        pictureBuffer.append(encoder.encode(b));  
        String codeBase64 = pictureBuffer.toString();  
        return codeBase64;  
    }  
    public static void main(String[] args) {
    	System.out.println("<img src='data:image/jpg;base64,"+QRCodeUtil.enCode("你好")+"' />");
	}
}  